<template>
  <el-upload
    ref="upload"
    action="#"
    :http-request="httpRequest"
    accept=".xls,.xlsx"
    :show-file-list="false"
    :before-upload="beforeUpload"
  >
    <el-button style="margin-top: 12px" size="small" type="warning">
      导入Excel
    </el-button>
    <div slot="tip" class="el-upload__tip">{{ tip }}</div>
  </el-upload>
</template>

<script>
import * as XLSX from "xlsx";
export default {
  name: "UploadExcel",
  data() {
    return {
      tip: "文件大小不能超过50kb",
    };
  },
  methods: {
    // 文件上传前
    beforeUpload(file) {
      this.tip = file.name;
    },
    // 文件上传
    httpRequest({ file }) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = e.target.result;
        // 读取二进制的excel
        const workbook = XLSX.read(data, { type: "binary" });
        return (this.studentsInfo = XLSX.utils.sheet_to_json(
          workbook.Sheets[workbook.SheetNames[0]]
        ));
      };
      reader.readAsBinaryString(file);
    },
  },
};
</script>
<style scoped></style>
